from logging import getLogger

from nevow.athena import LiveElement, expose
from nevow.flat import flatten
from nevow.loaders import stan
from nevow import tags

from zope.component import provideUtility, getUtilitiesFor, getGlobalSiteManager

from meercat.mapreduce import interfaces



__all__ = ['ActiveProcessList']

log = getLogger('meercat.server.nevow.elements.processing')

class ActiveProcessList(LiveElement):
    jsClass = u'Meercat.Multiprocessing.List'
    
    docFactory = stan(tags.div(render=tags.directive('liveElement'))[
        tags.ul(class_='MultiprocessingListActions actionList')[
            tags.li()[
                tags.a(href='#',
                       onclick="Nevow.Athena.Widget.get(this).refresh(); return false;")['Refresh List']]],
        tags.ul(class_='MultiprocessingList'),])
    
    @expose
    def getActiveList(self):
        log.info('%s.getActiveList()' % (str(self),))
        try:
            from multiprocessing import active_children
        except ImportError, e:
            log.error('Multiprocessing package is not available: %s' % (str(e),))
            return []
        
        return map(lambda p: {u'name': unicode(p.name),
                              u'pid': unicode(p.pid),
                              u'alive': p.is_alive()},
                   active_children())
